<template>
  <section :style="{height: $store.state.height + 'px'}" style="width: 100%;position: relative;">
    <div class="card" ref="content" style="width: 300px;">
      <div class="card-header" >
        添加坐标点
      </div>
      <div class="card-body">
        <p class="card-text">1.点击添加按钮</p>
        <p class="card-text">2.点击地图放置标记</p>
        <a href="#" class="btn btn-primary btn-block" @click="addEdits()">
          <i class="el-icon-plus"></i>
          添加
        </a>

        <div class="" v-show="isContent">
          <h5 class="mt-3 text-center">输入特征信息</h5>
          <div class="form-group">
            <label for="exampleInputEmail1">描述</label>
            <input type="text" class="form-control" v-model="desc">
            <small class="form-text text-muted">描述其实就是标题啦</small>
          </div>
          <div class="form-group">
            <label for="exampleInputPassword1">内容</label>
            <textarea class="form-control" rows="3" v-model="content"></textarea>
          </div>
          <button class="btn btn-success btn-block" @click="mapUpdate()">更新地图</button>
          <button class="btn btn-secondary btn-block" @click="mapDelete()">删除特征点</button>
        </div>
      </div>
    </div>
    <div id="dsc3" :style="{height: $store.state.height + 'px', width: '100%'}" ref="dsc3"></div>
  </section>
</template>

<script>
import { loadModules } from 'esri-loader'

// const url = 'http://10.1.3.42:6080/arcgis/rest/services/test/MapServer'
const url = 'http://10.1.3.42:6080/arcgis/rest/services/testserver/MapServer'

export default {
  name: "searchdraw",
  title: "绘制打点",
  data () {
    return {
      map: null,
      view: null,
      initialExtent: null,
      on: null,
      Graphic: null,
      editFeature: null,
      isContent: false,
      desc: '', // 描述
      content: '' // 内容

    }
  },
  mounted () {
    this.loadMap()
  },
  methods: {
    loadMap () {
      loadModules([
        "esri/Map",
        "esri/views/SceneView",
        "esri/layers/Layer",
        "esri/Graphic",
        "esri/widgets/Expand",
        "esri/widgets/Home",
        "esri/geometry/Extent",
        "esri/Viewpoint",
        "esri/core/watchUtils",
        "dojo/on",
        "dojo/domReady!"
      ]).then(([EsriMap, SceneView, Layer, Graphic, Expand, Home, Extent, Viewpoint, watchUtils, on]) => {
        window.on = on
        window.Graphic = Graphic

        this.map = new EsriMap({
          basemap: 'osm'
        })

        this.initialExtent = new Extent({
          xmin: -32045631,
          xmax: -25042853,
          ymin: 4034880,
          ymax: 4034881,
          spatialReference: 102100
        })

        this.view = new SceneView({
          container: "dsc3",
          map: this.map,
          extent: this.initialExtent
        })

        Layer.fromPortalItem({
            portalItem: { // autocasts as new PortalItem()
              id: "511b97fc0d364367b127f8ba5c89ad13"
            }
          }).then((layer) => {
            window.featureLayer = layer
            this.map.add(layer)
          }).catch((error) => {
            console.log('加载失败');
          })

        // set home buttone view point to initial extent
        let homeButton = new Home({
          view: this.view,
          viewpoint: new Viewpoint({
            targetGeometry: this.initialExtent
          })
        });
        this.view.ui.add(homeButton, "top-left")

        // expand widget
        let editExpand = new Expand({
          expandIconClass: "esri-icon-edit",
          expandTooltip: "Expand Edit",
          expanded: false,
          view: this.view,
          content: this.$refs.content
        })
        this.view.ui.add(editExpand, "top-right")

        this.view.when(() => {
          watchUtils.whenTrue(this.view, "stationary", () => {
            if (editExpand) {
              if (this.view.zoom <= 14) {
                editExpand.domNode.style.display = "none"
              } else {
                editExpand.domNode.style.display = "block"
              }
            }
          })
        })

        this.view.on("click", (event) => {
          this.unselectFeature()
          this.view.hitTest(event).then((response) => {
            if (response.results.length > 0 && response.results[0].graphic) {

              let feature = response.results[0].graphic;
              this.selectFeature(feature.attributes[featureLayer.objectIdField])

              this.desc = feature.attributes["Incident_Desc"]
              this.content = feature.attributes["Incident_Address"]
              this.isContent = true
            }
          })
        })
      })
    },
    applyEdits (params) {
      this.unselectFeature()
      let promise = featureLayer.applyEdits(params)
      this.editResultsHandler(promise)
    },
    editResultsHandler(promise) {
      promise.then((editsResult) => {
        let extractObjectId = function (result) {
          return result.objectId
        }
        // get the objectId of the newly added feature
        if (editsResult.addFeatureResults.length > 0) {
          var adds = editsResult.addFeatureResults.map(extractObjectId)
          let newIncidentId = adds[0]

          this.selectFeature(newIncidentId)
        }
      }).catch(function (error) {
        console.log("===============================================")
        console.error("[ applyEdits ] FAILURE: ", error.code, error.name, error.message)
        console.log("error = ", error)
      })
    },
    selectFeature(objectId) {
      // symbol for the selected feature on the view
      let selectionSymbol = {
        type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
        color: [0, 0, 0, 0],
        style: "square",
        size: "40px",
        outline: {
          color: [0, 255, 255, 1],
          width: "3px"
        }
      }
      let query = featureLayer.createQuery()
      query.where = featureLayer.objectIdField + " = " + objectId

      featureLayer.queryFeatures(query).then((results) => {
        if (results.features.length > 0) {
          this.editFeature = results.features[0]
          this.editFeature.symbol = selectionSymbol
          this.view.graphics.add(this.editFeature)
        }
      })
    },
    addEdits () {
      on.once(this.view, "click", (event) => {
        event.stopPropagation()
        if (event.mapPoint) {
          let point = event.mapPoint.clone()
          point.z = undefined
          point.hasZ = false

          let newIncident = new Graphic({
            geometry: point,
            attributes: {}
          });

          let edits = {
            addFeatures: [newIncident]
          }
          this.applyEdits(edits)
          this.isContent = true
          this.$refs.dsc3.style.cursor = "auto"
        }
      })
      this.$refs.dsc3.style.cursor = "crosshair"
    },
    mapUpdate () {
      if (this.editFeature) {
        this.editFeature.attributes["Incident_Desc"] = this.desc
        this.editFeature.attributes["Incident_Address"] = this.content

        var edits = {
          updateFeatures: [this.editFeature]
        }
        this.applyEdits(edits)
      }
    },
    mapDelete () {
      var edits = {
        deleteFeatures: [this.editFeature]
      };
      this.applyEdits(edits)
    },
    unselectFeature() {
      this.isContent = false
      this.desc = ''
      this.content = ''
      this.view.graphics.removeAll()
    }
  }
}
</script>

<style scoped>
  @import url('https://js.arcgis.com/4.8/esri/css/main.css');


</style>
